package routers

import (
	"fmt"
	"net/http"
	"path/filepath"
	"sync"

	"hermestrans/basis/middleware"
	config "hermestrans/internal/portal/config"
	mgr "hermestrans/internal/portal/manager"
	v1 "hermestrans/internal/portal/router/api"
	"hermestrans/internal/portal/router/home"

	"github.com/gin-gonic/gin"
)

var (
	routerOnce sync.Once
)

func initHome(conf *config.Config, handler *home.HomeHandler) *gin.Engine {
	route := gin.New()
	route.Use(middleware.ParseParams())
	route.Use(middleware.Trace())
	route.Use(gin.Recovery())
	gin.SetMode(conf.ServerConfig.RunMode)

	route.GET("/", handler.Home)                       //首页
	route.GET("/welcome", handler.Welcome)             //欢迎界面
	route.GET("/edit_password", handler.EditPassword)  //编辑密码
	route.POST("/save_password", handler.SavePassword) //保存密码

	// 设置模板解析函数
	//render, err := web.LoadTemplates(conf.ServerConfig.WebRoot)
	//if err != nil {
	//	return nil
	//}
	//route.HTMLRender = render //设置自定义模版加载

	//设置静态资源
	staticsFs := http.Dir(conf.ServerConfig.WebRoot + string(filepath.Separator) + "web" + string(filepath.Separator) + "statics")
	route.StaticFS("/statics", staticsFs)

	//route.LoadHTMLFiles(conf.ServerConfig.HTMLFiles)
	//route.LoadHTMLGlob(conf.ServerConfig.HTMLGlob)
	//route.Static(conf.ServerConfig.StaticRelativePath, conf.ServerConfig.StaticRoot)

	return route
}

func initRouter(route *gin.Engine, apiHandler *v1.ApiHandler,
	conf *config.Config) *gin.Engine {
	apiv1 := route.Group("/api/v1")
	{
		//作业相关操作
		apiv1.PUT("/jobs", apiHandler.HandleJobAdd)        //作业新增
		apiv1.PUT("/jobs", apiHandler.HandleJobsEdit)      //作业修改
		apiv1.DELETE("/jobs", apiHandler.HandleJobsDelete) //作业删除
		apiv1.GET("/jobs", apiHandler.HandleJobsGet)       //作业查询
	}

	return route
}

func InitRouter(conf *config.Config, mysql *mgr.MysqlMgr,
	mgo *mgr.MgoMgr, redis *mgr.RedisMgr) error {
	apiHandler := v1.NewApiHandler(conf, mgo)
	homeHandler := home.NewHandler(conf, mysql, redis)
	routerOnce.Do(func() {
		hroute := initHome(conf, homeHandler)
		route := initRouter(hroute, apiHandler, conf)

		s := &http.Server{
			Addr:           fmt.Sprintf(":%d", conf.ServerConfig.ApiPort),
			Handler:        route,
			ReadTimeout:    conf.ServerConfig.ApiReadTimeout,
			WriteTimeout:   conf.ServerConfig.ApiWriteTimeout,
			MaxHeaderBytes: 1 << 20,
		}
		s.ListenAndServe()
	})
	return nil
}
